#include "file_io.h"

#include <fstream>

#include "log.h"

namespace chat {
bool File::read(const std::string& filename, std::string* content) {
    std::ifstream in(filename, std::ios::binary | std::ios::in);
    if (!in.is_open()) {
        LOG_ERROR("{} 打开失败", filename);
        return false;
    }

    in.seekg(0, in.end);
    int length = in.tellg();
    in.seekg(0, in.beg);

    content->resize(length);

    if (!in.read(content->data(), length)) {
        LOG_ERROR("{} 读取失败", filename);
        return false;
    }

    in.close();

    return true;
}

bool File::write(const std::string& filename, const std::string& content) {
    std::ofstream out(filename, std::ios::binary | std::ios::out);
    if (!out.is_open()) {
        LOG_ERROR("{} 打开失败", filename);
        return false;
    }

    if (!out.write(content.c_str(), content.size())) {
        LOG_ERROR("{} 写入失败", filename);
        return false;
    }

    out.close();

    return true;
}
}  // namespace chat
